﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ManageModel.Model;
using System.Linq;

namespace ManageModel.Webapi.Middlewares
{
    /// <summary>
    /// 用于覆盖入参校验处理
    /// </summary>
    public class ValidFilter : IActionFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidFilter"/> class.
        /// </summary>
        public ValidFilter()
        {
        }
        /// <summary>
        /// 执行完成
        /// </summary>
        /// <param name="context">上下文对象</param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Method intentionally left empty.
        }
        /// <summary>
        /// Called before the action executes, after model binding is complete.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext" />.</param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // Method intentionally left empty.
            if (!context.ModelState.IsValid)
            {
                var msgList = context.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                context.Result = new JsonResult(new HttpReturnEntity { Code = "0", Message = string.Join(",", msgList) });
            }
        }
    }
}
